<!--企业合同签约账单预览对话框-->
<template>
	<a-modal v-bind="option" class="renter-bill-preview-dialog">
		<a-tabs v-model:activeKey="previewType" style="padding: 20px 16px">
			<a-tab-pane key="total" >
				<template #tab>
					<span>总账单</span>
					<loading-outlined v-show="loadings.total"/>

				</template>
				<total-bill-preview-table v-model:loading="loadings.total" :params="totalPreview">

				</total-bill-preview-table>
			</a-tab-pane>
			<a-tab-pane key="detail">
				<template #tab>
					<span>子账单</span>
					<!-- <span style="padding-left: 20px;">删除点什么</span> -->
				</template>
				<div style="padding: 20px 16px">
					<a-row :gutter="16" justify="space-between">
						<a-col :span="20">
							<a-select
								v-model:value="houseId"
								placeholder="请选择房间"
								:options="entity.enterPriseContractHouseRoomFroms"
								allow-clear
								show-search
								option-filter-prop="name"
								:field-names="{label: 'houseAddress', value: 'houseId'}"
								style="width: 100%"
								@change="changeHouse" />
						</a-col>

						<a-col :span="2">
							<a-button type="primary" @click="houseSwitch('up')">上一套</a-button>
						</a-col>

						<a-col :span="2">
							<a-button type="primary" @click="houseSwitch('down')">下一套</a-button>
						</a-col>
					</a-row>
				</div>

				<div class="bill-table-wrapper">
					<a-skeleton :loading="loadings.calc" active :paragraph="{rows: 13}">
						<template v-for="item in list" :key="item.num">
							<a-typography-paragraph strong>
								<blockquote>
									{{ item.name }}
								</blockquote>
							</a-typography-paragraph>
							<vxe-table :data="item.bills" v-bind="billTableOption" class="bill-preview-table">
								<vxe-column type="expand" title="期数" width="100">
									<template #default="{row}">第{{ row.num }}期</template>
									<template #content="{row}">
										<vxe-table :data="row.finances" :show-header="false">
											<vxe-column width="65">
												<template #default="{row: detail}">
													<svg-icon :icon-class="`finance-${detail.feeDirection == 1 ? 'in' : 'out'}`" />
													<span v-if="detail.feeDirection === 1" v-color="{color: 'primary'}">&nbsp;收</span>
													<span v-else v-color="{color: 'danger'}">&nbsp;付</span>
												</template>
											</vxe-column>
											<vxe-column min-width="200">
												<template #default="{row: detail}">
													{{ detail.feeSubjectName }}:
													<span v-color="{color: 'primary'}">{{ detail.amount.toLocaleString() }}</span>
													元
													<!--billType=2定金账单，不显示抵扣信息-->
													<template
														v-if="row.billType !== 2 && detail.occurredMoney > 0 && detail.feeDirection === 1">
														<a-tag color="processing" class="bill-carry-forward-tips">
															结转抵扣
															{{ detail.occurredMoney.toLocaleString() }}
															元， 抵扣后待收
															{{ detail.notOccurredMoney.toLocaleString() }}
															元
														</a-tag>
													</template>
												</template>
											</vxe-column>
											<vxe-column width="180">
												<template #default="{row}">付款日期:{{ row.payDate }}</template>
											</vxe-column>
											<vxe-column width="280">
												<template #default="{row}">费用周期:{{ row.beginDate }}至{{ row.endDate }}</template>
											</vxe-column>
										</vxe-table>
									</template>
								</vxe-column>
								<vxe-column field="billDate" title="账单日期" min-width="120" align="center" />
								<vxe-column title="账单周期" min-width="260" align="center">
									<template #default="{row}">{{ row.beginDate }}至{{ row.endDate }}</template>
								</vxe-column>
								<vxe-column field="totalAmount" title="金额" min-width="100" align="right">
									<template #default="{row}">{{ row.totalAmount.toLocaleString() }}</template>
								</vxe-column>
								<vxe-column title="操作" width="100" align="center">
									<template #default="{row}">
										<a>明细</a>
									</template>
								</vxe-column>
							</vxe-table>
						</template>
					</a-skeleton>
				</div>
			</a-tab-pane>
			<!-- <template #rightExtra>
				<span v-if="previewType === 'detail'">删除点什么</span>
			</template> -->
		</a-tabs>

		<template #footer>
			<a-button type="primary" :loading="loadings.save" :disabled="loadings.calc" @click="submit">保存</a-button>
		</template>
	</a-modal>
</template>

<script lang="ts" setup>
	import {computed, reactive, ref, toRef, watch} from 'vue'
	import {VxeTableProps} from 'vxe-table'
	import {CharterContract} from '@/interface/contract'
	import {
		change,
		insertEnterContract,
		renewalF,
		renterContractPreview,
		cal_merge_view,
		resubmitF,
		supplementaryAgreementF,
		childerResubmit
	} from '@/api/contract'
	import totalBillPreviewTable from './total-bill-preview-table.vue'
	import {LoadingOutlined,CloseOutlined} from '@ant-design/icons-vue'
	import {message} from 'ant-design-vue'
	import XEUtils from 'xe-utils'

	const props = defineProps<{
		visible: boolean
		contract: CharterContract
		// 是否为自定义优惠
		isCustomDiscount?: boolean
	}>()

	const entity = toRef(props, 'contract')

	const loadings = reactive({
		calc: false,
		total: false,
		save: false
	})

	const previewType = ref('total')

	const emits = defineEmits(['update:visible', 'success'])
	const option = reactive({
		width: 1100,
		title: '账单预览',
		centered: true,
		keyboard: false,
		maskClosable: false,
		destroyOnClose: true,
		visible: toRef(props, 'visible'),
		onCancel() {
			emits('update:visible', false)
		}
	})

	// 账单列表
	const list = ref<any[]>([])

	// 房子下标
	const houseIndex = ref<any>(0)
	const houseId = ref<any>()

	const getTotalPreviewParams = () => {
		return entity.value.enterPriseContractHouseRoomFroms.map(house => getPreviewParams(house))
	}

	const getPreviewParams = house => {
		const params = {
			isCustomize: 0,
			// 合同id 只在修改重新签约时传
			contractId:
				entity.value.contractId ||
				entity.value.contractPid ||
				entity.value.enterPriseContractHouseRoomFroms[houseIndex.value]?.contractId,
			contractPid: entity.value.contractPid || entity.value.enterPriseContractHouseRoomFroms[houseIndex.value]?.contractId,
			carryForward: entity.value.carryForward,
			carryForwardPrice: Math.abs(entity.value.deductionAmount || 0),
			beginTime: entity.value.beginTime,
			endTime: entity.value.endTime,
			payPattern: entity.value.payPattern,
			payPatternValue: entity.value.payPatternValue,
			depositMonth: entity.value.depositMonth,
			periodMonth: entity.value.periodMonth,
			oldDeposit: entity.value.oldDeposit,
			signType: entity.value.signType === 2 ? 2 : 1,
			cycleType: entity.value.cycleType,
			mergeType: entity.value.mergeType,
			otherExpenses: entity.value.otherExpenses || [],
			zeroRentPeriod: entity.value.zeroRentPeriod,
			// 手机号判断是否有预定，用于定金抵扣
			phone: entity.value.renterInfo?.phone,
			// 差异化
			houseId: house.houseId,
			//优惠前租金金额，自定义优惠租金直接取优惠后金额
			price: props.isCustomDiscount ? house.discountPrice : house.price,
			//优惠后租金金额
			discountPrice: house.discountPrice,
			// 押金不打折
			deposit: XEUtils.round(XEUtils.multiply(house.discountDeposit, entity.value.depositMonth || 0), 2),
			// 优惠id集合
			discountIds: entity.value.discountIds
		}

		// Feedisabled 增加的费用每个房间不一样，例如房型物业费，从房间里取
		params.otherExpenses.forEach(expense => {
			if (expense.Feedisabled) {
				expense.price = house.currentProperty
			}
		})

		return params
	}

	const getRenterContractPreview = () => {
		loadings.calc = true

		const house = entity.value.enterPriseContractHouseRoomFroms[houseIndex.value]

		const params = getPreviewParams(house)

		renterContractPreview(params)
			.then(({data = []}) => {
				list.value = data
			})
			.finally(() => (loadings.calc = false))
	}
	const getTotalData = () =>{
		const params =entity.value.enterPriseContractHouseRoomFroms.map(house=>getPreviewParams(house))
		cal_merge_view(params)
			.then(({data = []}) => {
				list.value = data
			})
			.finally(() => (loadings.calc = false))
	}

	const billTableOption = reactive<VxeTableProps>({
		size: 'medium',
		rowConfig: {
			isHover: true
		},
		expandConfig: {
			trigger: 'row',
			showIcon: false
		}
	})

	const houseSwitch = (type: string) => {
		if (type === 'up' && houseIndex.value === 0) {
			message.warn('已经是第一套了')
			return
		}
		if (type === 'down' && houseIndex.value === entity.value.enterPriseContractHouseRoomFroms.length - 1) {
			message.warn('已经是最后一套了')
			return
		}

		let number = type === 'up' ? -1 : 1
		houseIndex.value += number
		houseId.value = entity.value.enterPriseContractHouseRoomFroms[houseIndex.value]?.houseId

		getRenterContractPreview()
	}

	const changeHouse = (id: string) => {
		houseIndex.value = entity.value.enterPriseContractHouseRoomFroms.findIndex(item => item.id === id)

		getRenterContractPreview()
	}

	const actions: any = {
		// 新签、续签
		1: insertEnterContract,
		2: renewalF,
		// // 转租
		// 3: renterContractSublease,
		// // 换房
		4: change,
		// 补签
		5: insertEnterContract
	}

	// 提交合同
	const submit = () => {
		const actionType = (entity.value.signType || 1) as number

		const params: any = XEUtils.clone(entity.value, true)

		params.enterPriseContractHouseRoomFroms.forEach(o => {
			// 自定义优惠，金额直接取手动输入的金额
			o.price = props.isCustomDiscount ? o.discountPrice : o.price
			o.deposit = XEUtils.round(XEUtils.multiply(o.discountDeposit, entity.value.depositMonth || 0), 2)
		})

		loadings.save = true
		//新签 续租 补签
		if (!params.id) {
			let action = actions[actionType]

			if (actionType > 1) {
				delete params.id
			}

			// 换房特殊处理一下
			if (actionType === 4) {
				console.log('🚀 ~ file: renter-bill-preview-dialog.vue:264 ~ submit ~ info:', params)
				let enterContractInfo = XEUtils.clone(params || {}, true)
				params.enterContractInfo = enterContractInfo
				// 换房 重新提交 接口
				if (params.contractId) {
					action = childerResubmit
				}
			}

			// 判断是否是续租 如果是续租删除enterPriseContractHouseRoomFroms 增加 deliveryAddFormList simpleHouseList
			if (entity.value.signType === 2) {
				console.log(params.enterPriseContractHouseRoomFroms)
				params.simpleHouseList = params.enterPriseContractHouseRoomFroms?.map((e: any) => {
					return {
						houseId: e.houseId,
						price: e.price,
						discountPrice: e.discountPrice,
						deposit: e.deposit,
						houseDeliveryAddForm: e.deliveryAddForm || {}
					}
				})
				delete params.enterPriseContractHouseRoomFroms
			}

			if (action) {
				action(params)
					.then(({data}: any) => {
						// if (entity.value.signType === 2) {
						// 	//续租需要下发授权
						// 	extendAuthorization({id: data}).then(() => {
						// 		emits('success', '')
						// 		message.success('保存成功')
						// 		option.onCancel()
						// 	})
						// } else {
						// 	emits('success', data)
						// 	message.success('保存成功')
						// 	option.onCancel()
						// }
						emits('success', data)
						message.success('保存成功')
						option.onCancel()
					})
					.finally(() => (loadings.save = false))
			}
		} else {
			// 重新提交
			resubmitF(params)
				.then(({data}: any) => {
					loadings.save = false
					emits('success', data)
					message.success('保存成功')
					option.onCancel()
				})
				.finally(() => (loadings.save = false))
		}
	}
	const hideTotal = computed(()=>entity.value.enterPriseContractHouseRoomFroms.length <= 1)
	const totalPreview = ref({})
	watch(
		() => props.visible,
		() => {
			if (props.visible) {
				entity.value.mergeType = null
				entity.value.carryForward = false
				entity.value.paymentMethod = null
				houseIndex.value = 0
				houseId.value = entity.value.enterPriseContractHouseRoomFroms[0]?.houseId
				getRenterContractPreview()
				// getTotalData()
				// if(hideTotal.value){
					// previewType.value = hideTotal.value ? 'detail' :'total'

				// }
				totalPreview.value = getTotalPreviewParams()
			}
		}
	)
</script>

<style lang="less">
	.renter-bill-preview-dialog {
		.ant-modal-body {
			padding: 0;
			overflow: auto;
			height: 550px;
			position: relative;

			.vxe-toolbar {
				height: 50px;
				border-bottom: 1px solid @border-color-light;
			}

			.bill-table-wrapper {
				padding: 12px;

				.ant-typography:first-of-type blockquote {
					margin-top: 0;
				}

				.bill-preview-table {
					.vxe-body--expanded-column {
						border: none;

						.vxe-table--body-wrapper {
							margin-top: -1px;
							background: rgba(@primary-color, 0.05);

							.vxe-body--column {
								vertical-align: baseline;
							}
						}

						.svg-icon {
							width: 24px;
						}

						.bill-carry-forward-tips {
							left: 4px;
							position: relative;

							&:before {
								content: '';
								width: 8px;
								height: 8px;
								top: 6px;
								left: -4px;
								display: inline-block;
								position: absolute;
								transform: rotate(45deg);
								border: 1px solid transparent;
								background-color: inherit;
								border-left-color: inherit;
								border-bottom-color: inherit;
								border-radius: @border-radius-base;
							}
						}
					}
				}
			}
		}
	}
</style>
